<?php

Class Controller_Section Extends Controller_Base {
	function index() {
		echo "section";
	}
	
	function edit(){
		$d 	= $_POST;
		$id = isset($d['id'])?$d['id']:"";
		if($id=="")die('Error 100010223');
		$section 	= Section::get('',"",$id,"",'`author`,`name`,`descr`,`id`');
		$section	= $section[0];
		if(!(User::checkAccess("",$section['author'])))die('Ошибка доступа!!!');
		if(isset($d['form'])){
			$res['html'] 	= Template::parse('section/edit',$section);
			$res['title']	= "Редактирование секции - ".$section['name'];
			echo json_encode($res);
		}else{
			$v = Section::validate("",true);
			if($v['state']) {
				$data['descr'] 	= $d['descr'];
				$data['name'] 	= $d['name'];
				$res = Section::set("",$data,"",$id);
				if($res){
					$res = array("state" => true, "msg" => "Изменения сохранены.");
				}else{
					$res = array("state" => false, "msg" => "Изменения не сохранены!");
				}
				echo json_encode($res);
			} else {
				echo json_encode($v);
			}
		}
	}
	
	function delete(){
		$id = isset($_POST['id'])?$_POST['id']:"";
		if($id=="")die('Error 100010223');
		//$section = Section::get("","",$id,"",'`author`');
		if(!(User::checkAccess("admin")))die('Ошибка доступа!!!');
		Section::set(DB::$db, array("state"=>'-1',"delete_date"=>date('Y-m-d H:i:s')),"",$id);
		echo json_encode(array("state"=>"1"));
	}
	
	function delete_final(){
		$id = isset($_POST['id'])?$_POST['id']:"";
		if($id=="")die('Error 100010223');
		if(!(User::checkAccess("admin")))die('Ошибка доступа!!!');
		Section::delete($id);
		echo json_encode(array("state"=>"1"));
	}

	function new_() {
		if(!User::checkAccess('admin'))die('Ошибка доступа!!!');
		$db = DB::get();
		$d = $_POST;
		if(isset($d['form']) == true) {
			$res["title"] = "Создание новой секции";
			$res["html"] = Template::parse_("section/create");

			echo json_encode($res);
		} else {
			$v = Section::validate($db);
			if($v['state']) {
				$res = Section::create($db);
				echo json_encode($res);
			} else {
				echo json_encode($v);
			}
		}
	}

	function getByTag(){
		$d 				= $_POST;
		$id 			= isset($d['tag_id'])?$d['tag_id']:-1;
		$db 			= DB::get();
		if($id){
			$sections = Section::get($db,"",-1,"`tags` like '%".$id."%'");
			$res["title"] 	= "Секция".($id>=0?" ".$sections[0]['name']:"");
			$res["html"] 	= "".Section::getViewData($db,-1,$sections);
			if(isset($d['ajax'])){
				echo json_encode($res);
			}else{
				echo $res['html'];
			}
		}
	}

	function list_(){
		$d 				= $_POST;
		$id 			= isset($d['id'])?$d['id']:-1;
		$db 			= DB::get();
		$sections		= Section::get($db,"",$id);
		$res["title"] 	= "Секция".($id>=0?" ".$sections[0]['name']:"");
		$res["html"] 	= "".Section::getViewData($db,$id,$sections);
		if(isset($d['ajax'])){
			echo json_encode($res);
		}else{
			echo $res['html'];
		}
	}

}
?>